package com.shujia.mr.wc;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

/*
    reduce的输入key-value类型实际上就是map的输出key-value类型
 */
public class MyReducer extends Reducer<Text, LongWritable,Text, LongWritable> {
    //每一个分组都会执行一次reduce逻辑
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        //定义一个变量，接收加和
        long sum = 0;

        //作为wordcount案例，这里的reduce进入数据，是由一个单词和一个迭代器构成的
            //<"hello",[1,1,1,..]>
        //只需要遍历迭代器，将里面的值加起来就可以得到该单词出现次数
        for (LongWritable value : values) {
            //注意，LongWritable类型不能直接与long类型数据进行计算
            sum +=value.get();
        }
        //使用hadoop上下文对象，将结果写出到下一步
        context.write(key,new LongWritable(sum));
    }
}
